package com.example.demo.Service;

import com.example.demo.Dao.RecordRepository;
import com.example.demo.Entity.Record;
import com.example.demo.Vo.RecordVo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RecordService  {
    @Resource
    RecordRepository recordRepository;

    @SuppressWarnings({"serial" })
    public Page<Record> findByPageAndParams(int pageNumber, int pageSize,String theSort) {
        List<Sort.Order> orders = new ArrayList<>();
        if ("desc".equals(theSort)){
            orders.add(new Sort.Order(Sort.Direction.DESC, "recordDate"));
        }else {
            orders.add(new Sort.Order(Sort.Direction.ASC, "recordDate"));
        }
        Sort sort = Sort.by(orders);
        Pageable pageable =  PageRequest.of(pageNumber-1, pageSize,sort);
        return recordRepository.findAll( pageable);
    }
    public Page<Record> findByPageAndKeyword(int pageNumber, int pageSize,String theSort,String keyword) {

        Specification<Record> specification = null;
        specification = (Specification<Record>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (keyword != null && !"".equals(keyword)) {
                predicates.add(cb.like(root.<String>get("userName"), "%"+keyword+"%"));
                predicates.add(cb.like(root.<String>get("area"), "%"+keyword+"%"));
                predicates.add(cb.like(root.<String>get("workerName"),"%"+keyword+"%"));
            }
            return cb.or(predicates.toArray(new Predicate[predicates.size()]));
        };
        List<Sort.Order> orders = new ArrayList<>();
        if ("desc".equals(theSort)){
            orders.add(new Sort.Order(Sort.Direction.DESC, "recordDate"));
        }else {
            orders.add(new Sort.Order(Sort.Direction.ASC, "recordDate"));
        }
        Sort sort = Sort.by(orders);
        Pageable pageable =  PageRequest.of(pageNumber-1, pageSize,sort);
        return recordRepository.findAll(specification, pageable);
    }
}
